package com.tony.juc;

import java.lang.reflect.Constructor;
import java.util.concurrent.ThreadFactory;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: ThreadFactory
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/04/13:10
 * @Description:
 */
public class ThreadFactoryDemo {

    public static void main(String[] args) {

        /*for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println("线程名称：" + Thread.currentThread().getName());
            }).start();
        }*/

        /*for (int i = 0; i < 10; i++) {
            Thread thread = ThredFactoryDemo001.getInstance().newThread(()->{
                System.out.println("多线程执行：" + Thread.currentThread().getName());
            });
            thread.start();
        }*/

        for (int i = 0; i < 10; i++) {
            Thread thread = ThreadFactoryDemo002.getInstance().newThread(()->{
                System.out.println("多线程执行：" + Thread.currentThread().getName());
            });
            thread.start();
        }



    }

}
/**
* @Description: 创建线程工厂类
* @Param:
* @return:
* @Author: 皮蛋布丁
* @Date: 2022/4/4 14:13
*/
class ThredFactoryDemo001 implements ThreadFactory {

    private static final ThreadFactory INSTANCE = new ThredFactoryDemo001();
    private static final String TITLE = "Tony-";    //定义线程名称的开头
    private static int count = 0; //线程的自动计数处理
    private ThredFactoryDemo001(){} //工厂类在定义的时候一定不需要实例化对象

    //返回工厂实例
    public static ThreadFactory getInstance() {
        return INSTANCE;
    }

    @Override
    public Thread newThread(Runnable r) {   //此时的操作如果有需要可以进一步改进，例如：反射
        return new Thread(r,TITLE + count++);   //实例化THread类对象
    }
}

/**
* @Description: 创建线程工厂类
* @Param:
* @return:
* @Author: 皮蛋布丁
* @Date: 2022/4/4 14:24
*/
class ThreadFactoryDemo002 implements ThreadFactory {

    private static final ThreadFactory INSTANCE = new ThreadFactoryDemo002();
    private static final String TITLE = "Tony-";    //定义线程名称的开头
    private static int count = 0;   //线程的自动计数处理
    private ThreadFactoryDemo002(){}    //工厂类在定义的时候一定不需要实例化对象
    public static ThreadFactory getInstance() { //返回工厂实例
        return INSTANCE;
    }


    @Override
    public Thread newThread(Runnable r) {   //此时操作如果有需要可以进一步改进，例如：反射
        try {
            Class<?> clazz = Class.forName("java.lang.Thread");
            Constructor<?> constructor = clazz.getConstructor(Runnable.class, String.class);
            return (Thread) constructor.newInstance(r,TITLE + count++);  //实例化Thread类对象
        } catch (Exception e) {
            return null;
        }
    }
}
